package com.hnkjzyxy.ab.controller;

import Door.Access.Door8800.Command.System.Result.SearchEquptOnNetNum_Result;

import com.hnkjzyxy.ab.config.QuartzConfig;
import com.hnkjzyxy.ab.dto.ScheduleTaskDto;
import com.hnkjzyxy.ab.dto.WeeklyTimerRequest;
import com.hnkjzyxy.ab.model.LockInfo;
import com.hnkjzyxy.ab.model.ScheduleTask;
import com.hnkjzyxy.ab.model.SwitchRecord;
import com.hnkjzyxy.ab.result.ApiResult;
import com.hnkjzyxy.ab.service.ScheduleService;
import com.hnkjzyxy.ab.service.SmartLockService;
import com.hnkjzyxy.ab.service.SwitchRecordService;
import com.hnkjzyxy.ab.service.UserService;
import com.hnkjzyxy.ab.utils.NetworkInfo;
import com.hnkjzyxy.ab.utils.SearchDeviceCommand;
import com.hnkjzyxy.ab.utils.SmartLockSwitch;
import com.hnkjzyxy.ab.vo.UserVo;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.core.Authentication;

import javax.validation.Valid;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

import static java.lang.Thread.sleep;

@RestController
@RequestMapping("/smart/lock")
public class SamrtLockController {
    @Autowired
    SmartLockService smartLockService;
    HashSet<SearchEquptOnNetNum_Result.SearchResult> devicesList;
    @Autowired
    SwitchRecordService switchRecordService;
    @Autowired
    UserService userService;
    @Autowired
    private QuartzConfig quartzConfig;
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    @Autowired
    ScheduleService scheduleService;
    //查询所有锁信息
    @GetMapping("/selectAll")
    public ApiResult selectAll(){
        List<LockInfo> all = smartLockService.getAll();
        return ApiResult.ok("data",all);
    }
    //根据id查询锁信息
    @GetMapping("/getById")
    public ApiResult getById(@RequestParam("lockId") Integer lockId){
        LockInfo lockInfo = smartLockService.getById(lockId);
        return ApiResult.ok("data",lockInfo);
    }
    @GetMapping("/searchcheck")
    public void search() throws UnknownHostException {
        SearchDeviceCommand searchDeviceCommand = new SearchDeviceCommand();
        searchDeviceCommand.start();
        devicesList=searchDeviceCommand.getDevices();
    }
    //刷新锁设备记录
    @PostMapping("/insertLock")
    public ApiResult insertLock() throws UnknownHostException, InterruptedException {
        HashSet<LockInfo>devicelist=new HashSet<>(smartLockService.getAll());

        boolean flag=false;
        boolean result=false ;
        List<LockInfo> list=new ArrayList<>();
        if(devicelist.size()>=0){
            if(devicesList.size()>=0) {
                for (SearchEquptOnNetNum_Result.SearchResult device : devicesList) {
                    for (LockInfo lock : devicelist) {
                        if (lock != null && lock.getSnCode() != null) {
                            if (lock.getSnCode().equals(device.SN)) {
                                flag = true;
                            }
                        }
                    }
                    if (flag == false) {
                        LockInfo lockpojo = new LockInfo();
                        lockpojo.setIpAddress(device.TCP.GetIP());
                        lockpojo.setPortNumber(device.TCP.GetTCPPort());
                        lockpojo.setSnCode(device.SN);
                        System.out.println("设备信息：SN=" + device.SN + ",IP=" + device.TCP.GetIP() + ",TCPPort=" + device.TCP.GetTCPPort());
                        result = smartLockService.add(lockpojo);
                    }
                }
            }
        }
        if( result){
            return ApiResult.ok("添加成功");
        }
        return ApiResult.error("添加失败");
    }
    //修改锁信息
    @PostMapping("/updateLock")
    public ApiResult updateLock(@RequestBody LockInfo lockInfo){
        boolean result = smartLockService.update(lockInfo);
        if( result){
            return ApiResult.ok("修改成功");
        }
        return ApiResult.error("修改失败");
    }
    //更新锁状态
    @PostMapping("/updateSwitchStatus")
    public ApiResult updateSwitchStatus(@RequestBody LockInfo lockInfo,Authentication authentication) throws InterruptedException {
        LockInfo byId = smartLockService.getById(lockInfo.getLockId());
        UserVo userInfo = userService.getUserInfo(authentication.getName());
        boolean result = smartLockService.updateSwitchStatus(lockInfo.getLockId(), lockInfo.getSwitchStatus());
        if( result){
            if(byId!=null&&lockInfo.getSwitchStatus()==1){
                SmartLockSwitch.openDoor(byId.getIpAddress(),byId.getPortNumber(),byId.getSnCode());
                SwitchRecord switchRecord = new SwitchRecord();
                switchRecord.setOperationMethod(1);
                switchRecord.setLockId(byId.getLockId());
                switchRecord.setUserId(userInfo.getUserId());
                switchRecord.setOperationTime(LocalDateTime.now());
                switchRecordService.insert(switchRecord);
                //sleep(1000);
                new Thread(()->{
                    try {
                        sleep(3000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    switchRecord.setOperationMethod(0);
                    switchRecord.setOperationTime(LocalDateTime.now());
                    switchRecordService.insert(switchRecord);

                }).start();
                result = smartLockService.updateSwitchStatus(lockInfo.getLockId(),0);
                return ApiResult.ok("开锁成功");
            }
        }
        return ApiResult.error("更新失败");
    }
    //统计锁的数量
    @GetMapping("/countNum")
    public ApiResult countNum(){
        int num = smartLockService.countNum();
        return ApiResult.ok("ok",num);
    }
    //查询定时任务
    @GetMapping("/getTimer")
    public ApiResult getTimer(){
        List<ScheduleTask> all = scheduleService.getAll();
        return ApiResult.ok("data",all);
    }
    //根据时间查询定时任务
    @GetMapping("/getTimerByTime")
    public ApiResult getTimerByTime(@RequestParam("startTime")LocalDateTime startTime, @RequestParam("endTime")LocalDateTime endTime)
        {
            List<ScheduleTask> byTime = scheduleService.getByTime(startTime, endTime);
            return ApiResult.ok("data",byTime);
    }
    //根据id查询定时任务
    @GetMapping("/getTimerById")
    public ApiResult getTimerById(@RequestParam("id") Integer id){
        ScheduleTask byId = scheduleService.getById(id);
        return ApiResult.ok("data",byId);
    }
    //修改定时任务状态
    @PostMapping("/updateTimerStatus")
    public ApiResult updateTimerStatus(@RequestBody ScheduleTaskDto  scheduleTask) throws SchedulerException {
        ScheduleTask scheduleTaskTemp = trantoScheduleTask(scheduleTask);
        scheduleService.updateStatus(scheduleTaskTemp);
        if (scheduleService.updateStatus(scheduleTaskTemp)>0){
            return ApiResult.ok("修改成功");
        }
        return ApiResult.error("修改失败");
    }

    //添加定时任务到数据库
    @PostMapping("/addTimer")
    public ApiResult addTimer(@RequestBody ScheduleTaskDto scheduleTask, Authentication authentication) throws SchedulerException {
        // 获取用户信息
        UserVo userInfo = userService.getUserInfo(authentication.getName());
        // 验证锁是否存在
        LockInfo lockInfo = smartLockService.getById(scheduleTask.getLockId());
        if (lockInfo == null) {
            return ApiResult.error("锁不存在");
        }
        ScheduleTask scheduleTaskTemp = trantoScheduleTask(scheduleTask);
        scheduleService.insert(scheduleTaskTemp);
        // 生成Cron表达式
        String cronExpression = quartzConfig.generateWeeklyCronExpression(
                scheduleTask.getHour(),
                scheduleTask.getMinute(),
                scheduleTask.getCountDay()
        );

        // 创建任务和触发器
        JobDetail jobDetail = quartzConfig.createJobDetail(scheduleTask.getLockId(), userInfo.getUserId());
        Trigger trigger;
        if (scheduleTask.getLoopCount()>0){
            trigger = quartzConfig.createCronTrigger(jobDetail, cronExpression, scheduleTask.getLoopCount());
        }else{
            trigger= quartzConfig.createCronTrigger(jobDetail, cronExpression);
        }
        // 获取调度器并安排任务
        Scheduler scheduler = schedulerFactoryBean.getScheduler();

        // 先删除可能存在的同名任务
        if (scheduler.checkExists(jobDetail.getKey())) {
            scheduler.deleteJob(jobDetail.getKey());
        }

        scheduler.scheduleJob(jobDetail, trigger);

        return ApiResult.ok("每周定时任务已设置", cronExpression);

    }
    // 取消定时任务
    @PostMapping("/cancelWeeklyTimer")
    public ApiResult cancelWeeklyTimer(@RequestBody ScheduleTask scheduleTask) throws SchedulerException {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobKey jobKey = new JobKey("smartLockJob_" + scheduleTask.getLockId(), "smartLockGroup");

        if (scheduler.checkExists(jobKey)) {
            scheduler.deleteJob(jobKey);
            scheduleService.updateStatus(scheduleTask);
            return ApiResult.ok("定时任务已取消");
        }

        return ApiResult.error("未找到对应的定时任务");
    }
    public ScheduleTask trantoScheduleTask(ScheduleTaskDto scheduleTaskDto){
        // 将int数组转换为紧凑的逗号分隔字符串，例如: "1,2,3,4,5"
        StringBuilder countDayStr = new StringBuilder();
        int[] countDay = scheduleTaskDto.getCountDay();
        if (countDay != null && countDay.length > 0) {
            for (int i = 0; i < countDay.length; i++) {
                if (i > 0) countDayStr.append(",");
                countDayStr.append(countDay[i]);
            }
        }
        
        ScheduleTask scheduleTaskTemp = new ScheduleTask();
        scheduleTaskTemp.setLockId(scheduleTaskDto.getLockId());
        scheduleTaskTemp.setTaskId(scheduleTaskDto.getTaskId());
        scheduleTaskTemp.setTaskStatus(scheduleTaskDto.getTaskStatus());
        scheduleTaskTemp.setUserId(scheduleTaskDto.getUserId());
        scheduleTaskTemp.setTaskDetails(scheduleTaskDto.getTaskDetails());
        scheduleTaskTemp.setUpdatedTime(LocalDateTime.now());
        scheduleTaskTemp.setIsLoop(scheduleTaskDto.getIsLoop());
        scheduleTaskTemp.setHour(scheduleTaskDto.getHour());
        scheduleTaskTemp.setMinute(scheduleTaskDto.getMinute());
        scheduleTaskTemp.setCountDay(countDayStr.toString()); // 使用紧凑格式
        scheduleTaskTemp.setTimedOperation(scheduleTaskDto.getTimedOperation());
        scheduleTaskTemp.setRemarks(scheduleTaskDto.getRemarks());
        scheduleTaskTemp.setTaskStatus(scheduleTaskDto.getTaskStatus());
        scheduleTaskTemp.setCreatedTime(LocalDateTime.now());
        scheduleTaskTemp.setLoopCount(scheduleTaskDto.getLoopCount());

        return scheduleTaskTemp;
    }
}